<?php

class DBU_Db_Adapters_MySQL extends DBU_Db_Adapters_Abstract implements DBU_Db_Adapters_Interface {

	protected $connection;

	/**
	 * Connects to MySQL server
	 *
	 * @param string $host
	 * @param string $user
	 * @param string $password
	 * @param string $database
	 * @return resource
	 */
	public function connect($host = false, $user = false, $password = false, $database = false) {
		$this->connection = mysql_connect($host, $user, $password);

		if ($this->connection) {
			if (mysql_select_db($database, $this->connection)) {
				return $this->connection;
			} else {
				$message = 'Cannot select database ' . $database;
			}
		} else {
			$message = mysql_error();
		}

		if (!$this->connection) {
			throw new DBU_Db_Exception($message);
		}

		return false;
	}


   /**
	* Executes SQL query
	*
	* @param string $sql
	* @return result ID
	*/
	public function query($sql) {
		return mysql_query($sql, $this->connection);
	}


	public function lastInsertID() {
		return mysql_insert_id();
	}


	public function affectedRows() {
		return mysql_affected_rows($this->connection);
	}


	public function info() {
		return mysql_info($this->connection);
	}


	public function numRows($result) {
		return mysql_num_rows($result);
	}


	public function fetchArray($result) {
		return mysql_fetch_array($result);
	}


	public function fetchAssoc($result) {
		return mysql_fetch_assoc($result);
	}


	public function fetchObject($result) {
		return mysql_fetch_object($result);
	}


	public function result($result, $row, $field) {
		return mysql_result($result, $row, $field);
	}


	public function freeResults($result) {
		return mysql_free_result($result);
	}

	public function describeTable($table) {
		$return = array();
		$result = $this->execute('DESCRIBE ' . $table);

		if (mysql_num_rows($result)) {
			while ($row = $this->fetchAssoc($result)) {
				$return[$row['Field']] = array(
					'field'             => $row['Field'],
					'type'              => $row['Type'],
					'primary'           => ($row['Key'] == 'PRI'),
					'default'           => $row['Default'],
					'auto_increment'    => ($row['Extra'] == 'auto_increment')
					);
			}
		}
		return $return;
	}

    public function cleanData($data) {
        return mysql_real_escape_string($data, $this->connection);
    }
    
    public function error() {
    	return mysql_error();
    }
    

	public function disconnect() {
		mysql_close($this->connection);
	}
}